package cn.com.godliu.oauth2.config;

import cn.com.godliu.oauth2.service.AccountUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    AccountUserDetailsService accountUserDetailsService;

    /**
     * 配置认证方式，目前采用内存方式，后边改为数据库模式
     *
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //从数据库读取用户
        auth.userDetailsService(accountUserDetailsService);

        //从内测中配置用户信息和角色、权限
        //auth.inMemoryAuthentication()
        //        .passwordEncoder(bCryptPasswordEncoder)
        //        .withUser("wang").password(bCryptPasswordEncoder.encode("123")).roles("p1").authorities("admin","normal");

    }

    /**
     * 对web请求的一些配置
     *
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/register/**")    //放行这些以"/register/","/oauth/"开头请求
                .permitAll()
                .anyRequest()
                .authenticated()//所有请求都验证
                .and()
                .formLogin() //登录表单放过
                .permitAll()
                .and()
                .csrf().disable();//取消跨域
    }

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
}
